package com.ruoyi.web.controller.sysuserinviteimage;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.web.mapper.SysUserInviteImageMapper;
import com.ruoyi.web.pojo.SysUserInviteImage;
import com.ruoyi.web.util.TencentOssUploadUtils;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;
import java.util.UUID;
import org.springframework.mock.web.MockMultipartFile; // 确保引入这个类

@RestController
@RequestMapping("/uni/generate")
public class SysUserInviteImageController {
    // 微信 appId
    private static final String APP_ID = "wxbd664677f8367061";
    // 微信 AppSecret
    private static final String APP_SECRET = "b498ec52efbacda9913b7e717371a7fc";

    @Resource
    private SysUserInviteImageMapper sysUserInviteImageMapper;


    @PostMapping("/get/invite/img/records")
    public AjaxResult getInviteImgRecords(){
        return AjaxResult.success(sysUserInviteImageMapper.selectList(new LambdaQueryWrapper<SysUserInviteImage>()
                //用户编号
                .eq(SysUserInviteImage::getUserId, SecurityUtils.getUserId())));
    }


    @PostMapping("/get/invite/img")
    public AjaxResult getInviteImg(Long index){
        SysUserInviteImage sysUserInviteImage = sysUserInviteImageMapper.selectOne(new LambdaQueryWrapper<SysUserInviteImage>()
                //下标
                .eq(SysUserInviteImage::getMark, index)
                //用户编号
                .eq(SysUserInviteImage::getUserId, SecurityUtils.getUserId())
        );
        if (Objects.isNull(sysUserInviteImage)){
            return AjaxResult.error("用户海报不完整请联系管理员。");
        }
        //返回结果
        return AjaxResult.success(sysUserInviteImage.getInviteImg());
    }

    @PostMapping("/upload")
    public AjaxResult uploadTestFile3() throws Exception {
        //查询数据库
        SysUserInviteImage sysUserInviteImage = sysUserInviteImageMapper.selectOne(new LambdaQueryWrapper<SysUserInviteImage>()
                //用户编号
                .eq(SysUserInviteImage::getUserId, SecurityUtils.getUserId())
                //查询一条
                .last("limit 1")
        );
        if (Objects.nonNull(sysUserInviteImage)){
            //进入此处代表用户已经有自己的海报不用再次生成
            //返回姐u共
            return AjaxResult.success();
        }else{
            String accessToken = getAccessToken(); // 获取 Access Token

            Long userId = SecurityUtils.getUserId(); // 替换为实际的 userId

            byte[] qrCode = generateQr(accessToken, userId); // 生成二维码
            if (qrCode != null) {
                // 将二维码转换为 BufferedImage
                BufferedImage qrImage = ImageIO.read(new ByteArrayInputStream(qrCode));
                // 背景图片数组
                String[] backgroundUrls = {
                        "D:/wwwroot/private_domain_api/wwwroot/LiKLKImages/邀请1.jpg",
                        "D:/wwwroot/private_domain_api/wwwroot/LiKLKImages/邀请2.jpg",
                        "D:/wwwroot/private_domain_api/wwwroot/LiKLKImages/邀请3.jpg"
//                        "https://privatedomainapi.siyu99.com/LiKLKImages/邀请1.jpg",
//                        "https://privatedomainapi.siyu99.com/LiKLKImages/邀请2.jpg",
//                        "https://privatedomainapi.siyu99.com/LiKLKImages/邀请3.jpg"
                };

                // 二维码位置数组（每个二维码的 x 和 y 坐标）
                int[][] qrPositions = {
                        {500, 1850}, // 第一个二维码的位置
                        {940, 1905},  // 第二个二维码的位置
                        {945, 1935}    // 第三个二维码的位置
                };
                for (int i = 0; i < backgroundUrls.length; i++) {
                    // 加载背景图
//                    BufferedImage backgroundImage = ImageIO.read(new URL(backgroundUrls[i]));
                    BufferedImage backgroundImage = ImageIO.read(new File(backgroundUrls[i]));
                    System.out.println("Loading background image from: " + backgroundUrls[i]);
                    System.out.println("我是测试查看背景图" + backgroundImage.getWidth());
                    // 创建合成图像
                    BufferedImage combinedImage = new BufferedImage(backgroundImage.getWidth(), backgroundImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
                    Graphics g = combinedImage.getGraphics();
                    // 绘制背景图
                    g.drawImage(backgroundImage, 0, 0, null);
                    // 绘制二维码（增加二维码的大小）
                    int qrWidth = 220;  // 增加二维码宽度
                    int qrHeight = 220; // 增加二维码高度
                    int x = qrPositions[i][0]; // 获取二维码的 x 坐标
                    int y = qrPositions[i][1]; // 获取二维码的 y 坐标
                    g.drawImage(qrImage, x, y, qrWidth, qrHeight, null);
                    g.dispose();
                    //转换
                    MultipartFile uploadFile = convertBufferedImageToMultipartFile(combinedImage, "分享二维码.jpg");
                    //获取返回文件名
                    String fileName = TencentOssUploadUtils.uploadFile(uploadFile);
                    //设置url
                    String url = fileName;
                    System.out.println(url + "我是测试查看");
                    //执行添加
                    sysUserInviteImageMapper.insert(new SysUserInviteImage(null, SecurityUtils.getUserId(),url,i + 1));
                }
            }
            //返回姐u共
            return AjaxResult.success();
        }
    }

    // 将 BufferedImage 转换为 MultipartFile
    public static MultipartFile convertBufferedImageToMultipartFile(BufferedImage image, String fileName) throws IOException {
        // 第一步：将 BufferedImage 转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos); // 保存为 PNG 格式（可以根据需要更改格式）
        byte[] imageBytes = baos.toByteArray();
        // 第二步：创建 MultipartFile
        MultipartFile multipartFile = new MockMultipartFile(fileName, fileName, "image/png", imageBytes);
        return multipartFile;
    }

    public static byte[] generateQr(String accessToken, Long userId) {
        byte[] qrCodeData = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            String urlString = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken;
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            String jsonInputString = String.format("{\"path\": \"/pages/index/index?userid=%s\", \"width\": 430}", userId);
            System.out.println(userId + "我是测试查看userId" + jsonInputString);
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, bytesRead);
                }
                qrCodeData = baos.toByteArray();
            } else {
                System.err.println("Error: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return qrCodeData;
    }
    public static String getAccessToken() throws Exception {
        String urlString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        JSONObject jsonResponse = new JSONObject(response.toString());
        return jsonResponse.getString("access_token");
    }
}